#include "apdu_mac_manager.h"

#include "../../mk_lib/mk_utility.h"

#include <string.h>
#include <memory.h>
#include <stdlib.h>

apdu_mac_manager::apdu_mac_manager( void )
{

}

apdu_mac_manager::~apdu_mac_manager( void )
{

}

apdu * apdu_mac_manager::create_apdu_mac_init(int app_id, int container_id, int key_id, unsigned long alg_id,
													unsigned char * iv, int iv_len, 
													unsigned long padding_type, unsigned long feed_bit_len)
{
	apdu * newApdu = new apdu(SC_APDU_CASE_3_EXT, 0x80, 0xBC, 0, 0, "MacInit");
	
	unsigned char data[4096] = {0};

	int pos = 0;
	mk_utility::fill_buff_with_word_value_be(app_id, data);
	pos += 2;

	mk_utility::fill_buff_with_word_value_be(container_id, data + pos);
	pos += 2;

	mk_utility::fill_buff_with_word_value_be(key_id, data + pos);
	pos += 2;

	mk_utility::fill_buff_with_word_value_be(iv_len, data + pos);
	pos += 2;

	memcpy(data + pos, iv, iv_len);
	pos += iv_len;

	mk_utility::fill_buff_with_dword_value_be(padding_type, data +pos);
	pos += 4;

	mk_utility::fill_buff_with_dword_value_be(feed_bit_len, data +pos);
	pos += 4;

	newApdu->set_lc_data(data, pos);

	return newApdu;
}

apdu * apdu_mac_manager::create_apdu_mac(int app_id, int container_id, int key_id,  unsigned char * input, int input_len )
{
	apdu * newApdu = new apdu(SC_APDU_CASE_4_EXT, 0x80, 0xBE, 0, 0, "Mac");
	unsigned char data[4096] = {0};

	int pos = 0;
	mk_utility::fill_buff_with_word_value_be(app_id, data);
	pos += 2;

	mk_utility::fill_buff_with_word_value_be(container_id, data + pos);
	pos += 2;

	mk_utility::fill_buff_with_word_value_be(key_id, data + pos);
	pos += 2;

	memcpy(data + pos, input, input_len);
	pos += input_len;

	newApdu->set_lc_data(data, pos);

	return newApdu;
}

apdu * apdu_mac_manager::create_apdu_mac_update(int app_id, int container_id, int key_id, unsigned char * input, int input_len )
{
	apdu * newApdu = new apdu(SC_APDU_CASE_3_EXT, 0x80, 0xC0, 0, 0, "MacUpdate");
	unsigned char data[4096] = {0};

	int pos = 0;
	mk_utility::fill_buff_with_word_value_be(app_id, data);
	pos += 2;

	mk_utility::fill_buff_with_word_value_be(container_id, data + pos);
	pos += 2;

	mk_utility::fill_buff_with_word_value_be(key_id, data + pos);
	pos += 2;

	memcpy(data + pos, input, input_len);
	pos += input_len;

	newApdu->set_lc_data(data, pos);

	return newApdu;
}

apdu * apdu_mac_manager::create_apdu_mac_final(int app_id, int container_id, int key_id, unsigned char * input, int input_len)
{
	apdu * newApdu = new apdu(SC_APDU_CASE_4_EXT, 0x80, 0xC2, 0, 0, "MacFinal");
	unsigned char data[4096] = {0};

	int pos = 0;
	mk_utility::fill_buff_with_word_value_be(app_id, data);
	pos += 2;

	mk_utility::fill_buff_with_word_value_be(container_id, data + pos);
	pos += 2;

	mk_utility::fill_buff_with_word_value_be(key_id, data + pos);
	pos += 2;

	memcpy(data + pos, input, input_len);
	pos += input_len;

	newApdu->set_lc_data(data, pos);

	return newApdu;
}

